<?php
/*
 * Plugin Name: Javascript Playground
 * Plugin URI: http://cdiabu.edu
 * Description: Javacript + WordPress = Yay
 * Author: gradyetc
 * Author URI: http://grady-etc.com
 * License: GPL2
 */

/**
 * This plugin demonstrates a few different methods of adding Javascript files to pages
 * on your WordPress site and in the WordPress administrative back-end.
 * 
 * For a full list of Javascript libraries that are packaged with WordPress by default,
 * vist:
 * http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress
 */

// Example 1: wp_enqueueu_scripts will run while browsing the front end
add_action('wp_enqueue_scripts', 'jp_add_frontend_js' );

// Example 2: admin_enqueue_scripts will run while browsing the back end
add_action('admin_enqueue_scripts', 'jp_add_backend_js' );

// Example 3: admin_print_scripts-<file handle> will run while on the specified admin page
add_action('admin_print_scripts-post.php', 'jp_add_post_js' );
add_action('admin_print_scripts-post-new.php', 'jp_add_post_js' );

// Method 4: Passing data to Javascript the right way
add_action( 'wp_enqueue_scripts', 'jp_add_dynamic_js' );

/**
 * Run on template redirect (early enough to load custom Javascript, only run on front-end)
 * 
 * Adds custom Javascript file for frontend behavior modifications
 */
function jp_add_frontend_js( $hook_suffix ) {
        
        $src = plugins_url( 'js/jp-front.js', __FILE__ );
        
        wp_enqueue_script( 'jp-front', $src, array('jquery') );
}

/**
 * Run on admin_print_scripts
 * 
 * Adds custom Javascript file for backend behavior modifications
 */
function jp_add_backend_js( $hook_suffix ) {

        $src = plugins_url( 'js/jp-back.js', __FILE__ );

        wp_enqueue_script( 'jp-back', $src, array('jquery', 'jquery-ui-sortable' ) );

}

/**
 * Run on admin_print_scripts-edit and post-new.php
 * 
 * Conditionally adds Javascript only when adding or editing posts in the admin 
 */
function jp_add_post_js( $hook_suffix ) {
        
        $src = plugins_url( 'js/jp-post.js', __FILE__ );
        
        wp_enqueue_script( 'jp-post', $src, array('jquery') );
}

/**
 * Run on wp_print_scripts
 * 
 * Queues up custom javascript file and passes it some dynamic Server-Side data
 * 
 * @param type $hook_suffix 
 */
function jp_add_dynamic_js( $hook_suffix ) {
        
        $src = plugins_url( 'js/jp-dynamic.js', __FILE__ );
        
        wp_enqueue_script( 'jp-dynamic', $src, array('jquery') );       
        
        $params = array (
            'ajaxurl' => admin_url( 'admin-ajax.php', __FILE__ ),
            'hooksuffix' => $hook_suffix,
            'custom' => 'Hello, world!'
        );

        wp_localize_script( 'jp-dynamic', 'jp_data', $params );
}